package cn.yitun.chat.yitunservermanagecore.general.manage.server.service.impl;

import cn.yitun.chat.yitunservercommonlib.dataentity.data.server.ServerAddress;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.server.ServerData;
import cn.yitun.chat.yitunservercommonlib.dataentity.data.server.ServerType;
import cn.yitun.chat.yitunserverimbase.dao.server.ServerAddressDao;
import cn.yitun.chat.yitunserverimbase.dao.server.ServerTypeDao;
import cn.yitun.chat.yitunservermanagecore.general.manage.server.service.ServerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Date 2019-01-15 22:10:39<br>
 * Description
 * @author yitun<br>
 * @since 1.0
 */
@Service
public class ServerServiceImpl implements ServerService {

	private List<ServerData> configServerDataList;
	@Resource
	private ServerTypeDao serverTypeDAO;
	@Resource
	private ServerAddressDao serverAddressDAO;

	/**
	 * 
	 * Date 2019-01-15 22:19:51<br>
	 * Description 获取服务端信息列表
	 * @author yitun<br>
	 * @since 1.0
	 */
	public List<ServerData> getServerDataList() {
		List<ServerData> list = new ArrayList<>();
		List<ServerType> serverTypelist = serverTypeDAO.list(null);
		List<ServerAddress> serverAddresslist = serverAddressDAO.list(null);

		Map<String, ServerData> codeMap = new HashMap<>();
		if (null != configServerDataList) {
			for (ServerData sd : configServerDataList) {
				codeMap.put(sd.getCode(), sd);
			}
		}

		Map<Long, ServerData> map = new HashMap<>();
		for (ServerType st : serverTypelist) {
			if ("1".equals(st.getEnabled())) {
				String code = st.getCode();
				ServerData sd = codeMap.remove(code);
				if (null == sd) {
					sd = new ServerData();
				}
				if (null == sd.getAddressList()) {
					sd.setAddressList(new ArrayList<>());
				}
				sd.setName(st.getName());
				sd.setCode(st.getCode());
				sd.setDescription(st.getDescription());
				map.put(st.getId(), sd);
			}
		}

		for (ServerAddress sa : serverAddresslist) {
			if ("1".equals(sa.getEnabled())) {
				ServerData sd = map.get(sa.getServerTypeId());
				if (sd != null) {
					sd.getAddressList().add(sa);
				}
			}
		}
		
		list.addAll(codeMap.values());
		list.addAll(map.values());
		return list;
	}

	/**
	 * 保存
	 * @param serverType
	 */
	public void saveOrUpdate(ServerType serverType) {
		if (serverType.getId() == null)
			serverTypeDAO.save(serverType);
		else
			serverTypeDAO.update(serverType);
	}

	public List<ServerData> getConfigServerDataList() {
		return configServerDataList;
	}

	public void setConfigServerDataList(List<ServerData> configServerDataList) {
		this.configServerDataList = configServerDataList;
	}

}
